var viewData = {};
var show = {};

$('.func-erp li').click(function () {
    $('.func-erp li').removeClass('funcLI');
    $(this).addClass('funcLI');
})

$('#qiye').click(function () {
    show.qiye = !show.qiye;
    show.qiyem = !show.qiyem;
    if (show.qiye && !viewData.qiye && show.qiyem && !viewData.qiyem) {
        viewData.qiye = sgworld.Creator.createGeojsonFeatureLayer('企业点', {
            url: './geojson/qiye.geojson'
        }, {
            billboard: {
                image: './static/IMG/mark1.png',
                scale: 0.5,
                heightReference: 1
            }
        }, 0, true, function () {

        });

        viewData.qiyem = sgworld.Creator.createGeojsonFeatureLayer('企业面', {
            url: './geojson/qiyem.geojson'
        }, {
            polygon: {
                material: '#ffffff50',
                outlineColor: '#ffffff',
                height: 30,
            }
        }, 0, true, function (dataSource) {
            let entities = dataSource.entities.values;
            viewData.qiyem.entities = entities;
            for (let i = 0; i < entities.length; i++) {
                let entity = entities[i];
                entity._properties.addProperty('id', 'qiye' + i);
            }
        });
        !show.isPick && pickQiYeData();
        return;
    }
    sgworld.ProjectTree.setVisibility(viewData.qiye.treeobj.id, show.qiye);
    sgworld.ProjectTree.setVisibility(viewData.qiyem.treeobj.id, show.qiyem);
});
$('#pick').click(function () {
    pickQiYeData();
});

$('#model').click(function () {
    show.model = !show.model;
    sgworld.ProjectTree.setVisibility(viewData.model.treeobj.id, show.model);
});

var num = 1;
//拾取信息
function pickQiYeData() {
    if (!show.isPick) {
        !viewData.tooltip && (viewData.tooltip = sgworld.Core.CreateTooltip({ origin: 'center' }));
        viewData.pickHandler = sgworld.AttachEvent('OnFrame', function (movement) {
            var pick = sgworld._Viewer.scene.pick(movement.endPosition);
            //选中某模型   pick选中的对象
            if (Cesium.defined(pick) && pick.id) {
                if (pick.id._properties) {
                    let value, _properties;
                    viewData.thisPick = pick.id;
                    if (viewData.thisSelect && viewData.thisSelect == viewData.thisPick) {
                        document.body.style.cursor = "pointer";
                        viewData.tooltip.show(false);
                        return;
                    }
                    _properties = pick.id._properties;
                    if (_properties.wzxq) {
                        value = '<div style="font-family:微软雅黑;font-weight: bolder;font-size: 20px;padding:8px;">' + _properties._TE_DESC.getValue() + '</div>' +
                            '<div style="font-family:黑体;font-weight: bolder;font-size: 15px;padding:2px 8px;">所选应急物资库存场所:</div><br>' +
                            '<div style="font-family:微软雅黑;font-weight: bolder;font-size: 18px;padding:6px;">' + _properties.wzxq.getValue() + '</div>';
                    } else {
                        _properties._TE_DESC && (value = _properties._TE_DESC.getValue());
                        _properties.name && (value = _properties.name.getValue());
                    }
                    value && viewData.tooltip.showAt(movement.endPosition, value);
                    document.body.style.cursor = "pointer";
                } else {
                    viewData.thisPick = undefined;
                    viewData.tooltip.show(false);
                    document.body.style.cursor = "auto";
                }
            } else {
                viewData.thisPick = undefined;
                viewData.tooltip.show(false);
                document.body.style.cursor = "auto";
            }
        });
        !viewData.resultTooltip && (viewData.resultTooltip = sgworld.Core.CreateResultTooltip(Viewer));
        viewData.pickHandler.setInputAction(function (movement) {
            if (viewData.thisPick) {
                if (viewData.thisSelect && viewData.thisSelect == viewData.thisPick) {
                    return;
                }
                let pickData = getEntityData(viewData.thisPick);
                if (!pickData || !pickData.id || (pickData.id && pickData.id.indexOf('qiye') === -1)) {
                    if (viewData.thisShowWindow && viewData.thisShowWindow.thisTap) {
                        let thisTap = viewData.thisShowWindow.thisTap;
                        if (thisTap === 'danger_source') {
                            viewData.thisShowWindow.dangerData && viewData.thisShowWindow.dangerData.polygon && viewData.thisShowWindow.dangerData.polygon.material.color.setValue(Cesium.Color.WHITE.withAlpha(0.5));
                            viewData.thisShowWindow.dangerData = viewData.thisPick;
                            viewData.thisShowWindow.dangerData.polygon && viewData.thisShowWindow.dangerData.polygon.material.color.setValue(Cesium.Color.RED.withAlpha(0.2));
                            viewData.resultTooltip.showAt(sgworld.Navigate.getMousePosition(movement), pickData.name + '/' + pickData.qiye + '/' + pickData.level + '重大危险源');
                        } else if (thisTap === 'crafts') {
                            viewData.resultTooltip.show(false);
                            viewData.thisShowWindow.craftsData && viewData.thisShowWindow.craftsData.billboard && viewData.thisShowWindow.craftsData.billboard.scale.setValue(0.5);
                            viewData.thisShowWindow.craftsData = viewData.thisPick;
                            viewData.thisShowWindow.craftsData.billboard && viewData.thisShowWindow.craftsData.billboard.scale.setValue(0.8);
                            viewData.thisShowWindow.craftsData && showChartData(viewData.thisShowWindow.craftsData.position.getValue(), pickData.qiye + '/' + pickData.name + '/' + pickData.gy);
                        } else if (thisTap === 'danger_goods') {
                            viewData.resultTooltip.show(false);
                            viewData.thisShowWindow.DangerGoodsData && viewData.thisShowWindow.DangerGoodsData.billboard && viewData.thisShowWindow.DangerGoodsData.billboard.scale.setValue(0.5);
                            viewData.thisShowWindow.DangerGoodsData = viewData.thisPick;
                            viewData.thisShowWindow.DangerGoodsData.billboard && viewData.thisShowWindow.DangerGoodsData.billboard.scale.setValue(0.8);
                            viewData.thisShowWindow.DangerGoodsData && showChartData(viewData.thisShowWindow.DangerGoodsData.position.getValue(), pickData.qiye + '/' + pickData.name + '/' + pickData.whp + '/' + pickData.num);
                        } else if (thisTap === 'danger_area') {
                            viewData.thisShowWindow.DangerAreaData && viewData.thisShowWindow.DangerAreaData.polygon && viewData.thisShowWindow.DangerAreaData.polygon.outlineColor.setValue(Cesium.Color.WHITE.withAlpha(0));
                            viewData.thisShowWindow.DangerAreaData = viewData.thisPick;
                            viewData.thisShowWindow.DangerAreaData.polygon && viewData.thisShowWindow.DangerAreaData.polygon.outlineColor.setValue(Cesium.Color.WHITE.withAlpha(1));
                            viewData.resultTooltip.showAt(sgworld.Navigate.getMousePosition(movement), pickData.qiye + '/' + pickData.name);
                        }
                    } else if (pickData.wzxq) {
                        popupRes('物资详情', 550, 600, 'HTML/wzxq.html', null);
                    }
                    return;
                }
                viewData.tooltip && viewData.tooltip.show(false);
                let position = sgworld.Navigate.getMousePosition(movement);
                viewData.resultTooltip.showAt(position, pickData["TE_DESC"] || pickData["name"]);
                viewData.pickData = pickData;

                popupRes('基本信息', 500, 800, 'HTML/biote.html', {
                    cancel: () => {
                        viewData.resultTooltip.show(false);
                        viewData.thisSelect && viewData.thisSelect.polygon && viewData.thisSelect.polygon.material.color.setValue(viewData.originColor);
                        viewData.thisSelect = undefined;
                        viewData.thisShowWindow && viewData.thisShowWindow.recover(), viewData.thisShowWindow = undefined;
                    }
                });
                viewData.thisSelect && viewData.thisSelect.polygon && viewData.thisSelect.polygon.material.color.setValue(viewData.originColor);
                viewData.thisSelect = viewData.thisPick;
                if (viewData.thisSelect.polygon) {
                    viewData.originColor = viewData.thisSelect.polygon.material.color.getValue();
                    viewData.thisSelect.polygon.material.color.setValue(Cesium.Color.LIGHTYELLOW.withAlpha(0));
                    sgworld.Navigate.flyToObj(viewData.thisSelect);
                }
            } else if (sgworld._Viewer.scene.pick(movement.position)) {
                let pick = sgworld._Viewer.scene.pick(movement.position);
                if (pick.id && pick.id.isYQ && !pick.id.divObj) {
                    pick.id.divObj = sgworld.Creator.createDivPoint('阈值：3' + num, { x: pick.id.lon, y: pick.id.lat, z: pick.id.H }, 0, undefined, { url1: './static/IMG/divpoint1.png' });
                    pick.id.divObj.minLevel = 19;
                    pick.id.divObj.maxLevel = 25;
                    num += 3
                }
            } else {
                viewData.resultTooltip.show(false);
                viewData.thisSelect && viewData.thisSelect.polygon && viewData.thisSelect.polygon.material.color.setValue(Cesium.Color.WHITE.withAlpha(0.5));
                viewData.thisSelect = undefined;
                viewData.thisShowWindow && viewData.thisShowWindow.recover(), viewData.thisShowWindow = undefined, layer.close(layerRes);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        show.isPick = true;
    } else {
        show.isPick = false;
        viewData.pickHandler && viewData.pickHandler.destroy();
        viewData.tooltip && viewData.tooltip.show(false);
        document.body.style.cursor = "auto";
    }
}

//定位
$("#position").click(() => {
    sgworld.Navigate.flyToPosition(117.57844128806192, 38.35974915512376, 15829)
});

//定位
$("#modelPosition").click(() => {
    sgworld.Navigate.flyToPointsInterest({
        destination: new Cesium.Cartesian3.fromDegrees(117.61236268047885, 38.34989825257194, 89),
        orientation: {
            heading: 5.550698117131254,
            pitch: -0.38803023506455814,
            roll: 0
        }
    });
});

//企业分级
$("#qiyefenji").click(() => {
    if (viewData.qiyem && viewData.qiyem.entities) {
        viewData.qiyem.isFourColor = !viewData.qiyem.isFourColor;
        let entities = viewData.qiyem.entities;
        for (let i = 0; i < entities.length; i++) {
            let entity = entities[i];
            let data = getEntityData(entity);
            viewData.qiyem.isFourColor && entity.polygon && entity.polygon.material.color.setValue(Cesium.Color.fromCssColorString(data.color).withAlpha(0.5));
            !viewData.qiyem.isFourColor && entity.polygon && entity.polygon.material.color.setValue(Cesium.Color.WHITE.withAlpha(0.5));
        }
    }
});

//聚合
$("#wzjh").click(() => {
    !show.isPick && pickQiYeData();
    show.wzjh = !show.wzjh;
    show.wzxq = !show.wzxq;
    if (show.wzjh && !viewData.wzjh && show.wzxq && !viewData.wzxq) {
        viewData.wzjh = sgworld.Creator.createGeojsonFeatureLayer('物资聚合', {
            url: './geojson/yingjiwuzi.geojson',
            maxLevel: 14,
            minLevel: 12
        }, {
            label: {
                backgroundColor: Cesium.Color.WHITE.withAlpha(0.8),
                fillColor: Cesium.Color.BLACK,
                font: '微软雅黑',
                scale: 1,
                showBackground: true,
                heightReference: 1
            }
        }, 0, true, function (dataSource) {
            let entities = dataSource.entities.values;
            viewData.wzjh.entities = entities;
            for (let i = 0; i < entities.length; i++) {
                let entity = entities[i];
                entity.billboard = undefined;
                entity.label.text = entity._properties.TE_TEXT.getValue();
            }
        });

        viewData.wzxq = sgworld.Creator.createGeojsonFeatureLayer('物资详情', {
            url: './geojson/wuzixiangqing.geojson',
            maxLevel: 25,
            minLevel: 15
        }, {
            billboard: {
                image: './static/IMG/warring.png',
                scale: 0.5,
                heightReference: 1
            }
        }, 0, true, function (dataSource) {
            let entities = dataSource.entities.values;
            viewData.wzxq.entities = entities;
        })
        return;
    }
    sgworld.ProjectTree.setVisibility(viewData.wzjh.treeobj.id, show.wzjh);
    sgworld.ProjectTree.setVisibility(viewData.wzxq.treeobj.id, show.wzxq);
});

var wx_circle;
$("#wxmn").click(() => {
    var lon = 117.61057941973748;
    var lat = 38.3517722592473;
    var circle;
    var ksy = function () {
        del();
        sgworld.Core.setDepthTest('open', Viewer);
        wx_circle = sgworld.Analysis.createCircleScan({ lon: lon, lat: lat }, 200, '#ff0000', 3000);
    };
    var del = function () {
        wx_circle && wx_circle.remove();
        wx_circle = undefined;
        sgworld.Core.setDepthTest('close', Viewer);
    };
    if (wx_circle) {
        del();
    } else {
        ksy();
    }
});

//传感器
$("#cgq").click(() => {
    show.model1 = !show.model1;
    show.model2 = !show.model2;
    show.model3 = !show.model3;
    sgworld.ProjectTree.setVisibility(viewData.model1.treeobj.id, show.model1);
    viewData.model1.item.divObj && sgworld.ProjectTree.setVisibility(viewData.model1.item.divObj.treeobj.id, show.model1);
    sgworld.ProjectTree.setVisibility(viewData.model2.treeobj.id, show.model2);
    viewData.model2.item.divObj && sgworld.ProjectTree.setVisibility(viewData.model2.item.divObj.treeobj.id, show.model2);
    sgworld.ProjectTree.setVisibility(viewData.model3.treeobj.id, show.model3);
    viewData.model3.item.divObj && sgworld.ProjectTree.setVisibility(viewData.model3.item.divObj.treeobj.id, show.model3);
    show.model1 && sgworld.Navigate.flyToPointsInterest({
        destination: new Cesium.Cartesian3.fromDegrees(117.60858722762212, 38.35209778664259, 31.475845876189318),
        orientation: {
            heading: 3.656876521630492,
            pitch: -0.41636979777717786,
            roll: 0
        }
    });
});

//缓冲区
$("#hcq").click(() => {
    viewData.buff && viewData.buff.clearBuff(), showBufferData(false);
    viewData.buff = sgworld.Analysis.DrawPointBuffer(180, function (degrees) {
        showBufferData(true, degrees);
    });
});

//缓冲区清除
$("#hcq_clear").click(() => {
    viewData.buff && viewData.buff.clearBuff(), showBufferData(false);
});

function showBufferData(isShow, degrees) {
    if (isShow && viewData.wzxq && viewData.wzxq.entities) {
        !viewData.wzxq.BufferData && (viewData.wzxq.BufferData = []);
        let _position = Cesium.Cartesian3.fromDegrees(degrees.lon, degrees.lat, 0);
        let distance;
        viewData.wzxq.entities.forEach(item => {
            let position = item.position.getValue();
            distance = sgworld.Core.getSpaceDistancem([_position, position], Cesium);
            if (distance < 180) {
                if (item.divObj) {
                    sgworld.ProjectTree.setVisibility(item.divObj.treeobj.id, true);
                } else {
                    var cartographic = Cesium.Cartographic.fromCartesian(position);
                    var longitude = Cesium.Math.toDegrees(cartographic.longitude);
                    var latitude = Cesium.Math.toDegrees(cartographic.latitude);
                    let data = getEntityData(item);
                    let divObj = sgworld.Creator.createDivPoint(data.TE_DESC, { x: longitude, y: latitude, z: cartographic.height }, 0, undefined, { url1: './static/IMG/divpoint1.png' });
                    divObj.minLevel = 15;
                    divObj.maxLevel = 25;
                    item.divObj = divObj;
                    viewData.wzxq.BufferData.push(divObj);
                }
            }
        });
    } else {
        if (viewData.wzxq.BufferData) {
            viewData.wzxq.BufferData.forEach(item => {
                sgworld.ProjectTree.setVisibility(item.treeobj.id, false);
            });
        }
    }
}

//重大危险源
function showDangerData(isShow) {
    show.danger = isShow;
    if (show.danger && !viewData.danger) {
        viewData.danger = sgworld.Creator.createGeojsonFeatureLayer('重大危险源', {
            url: './geojson/zhongdaweixianyuan.geojson'
        }, {
            polygon: {
                material: '#ffffff50',
                outlineColor: '#ff0000',
                height: 30,
            }
        }, 0, true, function (dataSource) {
            let entities = dataSource.entities.values;
            viewData.danger.entities = entities;
            for (let i = 0; i < entities.length; i++) {
                let entity = entities[i];
                //polygon
                if (entity.polygon != undefined) {
                    let data = getEntityData(entity);
                    data.color && (entity.polygon.outlineColor = Cesium.Color.fromCssColorString(data.color));
                }
            }
        })
        return;
    }
    sgworld.ProjectTree.setVisibility(viewData.danger.treeobj.id, isShow);
}

//重点工艺
function showCraftsData(isShow) {
    show.crafts = isShow;
    if (show.crafts && !viewData.crafts) {
        viewData.crafts = sgworld.Creator.createGeojsonFeatureLayer('重点工艺', {
            url: './geojson/zhongdiangongyi.geojson'
        }, {
            billboard: {
                image: './static/IMG/point1.png',
                scale: 0.5,
                heightReference: 1
            }
        }, 0, true, function (dataSource) {
            let entities = dataSource.entities.values;
            viewData.crafts.entities = entities;
        })
        return;
    }
    sgworld.ProjectTree.setVisibility(viewData.crafts.treeobj.id, isShow);
}

//重点危化品
function showDangerGoodsData(isShow) {
    show.DangerGoods = isShow;
    if (show.DangerGoods && !viewData.DangerGoods) {
        viewData.DangerGoods = sgworld.Creator.createGeojsonFeatureLayer('重点危化品', {
            url: './geojson/zhongidanweihuapin.geojson'
        }, {
            billboard: {
                image: './static/IMG/point.png',
                scale: 0.5,
                heightReference: 1
            }
        }, 0, true, function (dataSource) {
            let entities = dataSource.entities.values;
            viewData.DangerGoods.entities = entities;
        })
        return;
    }
    sgworld.ProjectTree.setVisibility(viewData.DangerGoods.treeobj.id, isShow);
}

//风险区域
function showDangerAreaData(isShow) {
    show.DangerArea = isShow;
    if (show.DangerArea && !viewData.DangerArea) {
        viewData.DangerArea = sgworld.Creator.createGeojsonFeatureLayer('风险区域', {
            url: './geojson/fengxiansisetu.geojson'
        }, {
            polygon: {
                material: '#ffffff50',
                outlineColor: '#ffffff00',
                height: 30,
            }
        }, 0, true, function (dataSource) {
            let entities = dataSource.entities.values;
            viewData.DangerArea.entities = entities;
            for (let i = 0; i < entities.length; i++) {
                let entity = entities[i];
                //polygon
                if (entity.polygon != undefined) {
                    let data = getEntityData(entity);
                    data.color && (entity.polygon.material = Cesium.Color.fromCssColorString(data.color).withAlpha(0.5));
                }
            }
        })
        return;
    }
    sgworld.ProjectTree.setVisibility(viewData.DangerArea.treeobj.id, isShow);
}

function getEntityData(entity) {
    if (!entity._properties) {
        return {};
    }
    let _properties = entity._properties;
    let propertyNames = _properties.propertyNames;
    let data = {};
    propertyNames.forEach(item => {
        data[item] = _properties[item].getValue();
    });
    return data;
}

function getPolygon() {
    var arr = [];
    sgworld.AttachOnLButtonDownEvent(function (x, y, movement) {
        arr.push([x, y]);
    });
    sgworld.AttachOnRButtonDownEvent(function (x, y, movement) {
        arr.push(arr[0]);
        console.log(arr);
        arr = [];
    });
}

//图标数据
function showChartData(position, value) {
    viewData.chartPosition = position;
    // popupProp(value, 500, 310, 'HTML/echart.html', {
    //     success: function (layero) {
    //         viewData.chartPosition = position;
    //         viewData.chartDiv = layero[0];
    //         var CanvasCoordinates = Viewer.scene.cartesianToCanvasCoordinates(viewData.chartPosition);
    //         if (!CanvasCoordinates) return;
    //         let _x = -viewData.chartDiv.offsetWidth / 2;
    //         let _y = 80;
    //         viewData.chartDiv.style.left = CanvasCoordinates.x + _x + "px";
    //         viewData.chartDiv.style.top = CanvasCoordinates.y + _y + "px";
    //     }
    // });
    if (!viewData.addChartData) {
        viewData.addChartData = true;
        var html = '<div id="ChartData" style="pointer-events: none;position: absolute;z-index: 1000;opacity: 0.8;border-radius: 4px;background: rgba(42,44,64,.7);"></div>';
        $('.cesium-viewer').append(html);
        viewData.chartDiv = document.getElementById('ChartData');
        viewData.chartDiv.innerHTML = '<div id="ChartDataTitle" style="white-space: nowrap;font-family:黑体;font-weight: bolder;font-size: 14px;color: white;padding: 4px 8px;border-bottom: 1px solid;"></div><iframe src="HTML/echart.html" style="height: 268px;width: 500px;border: unset;"></iframe>';
        viewData.ChartDataTitle = document.getElementById('ChartDataTitle');

        Viewer.scene.camera.changed.addEventListener(function () {
            if (viewData.chartPosition && viewData.chartDiv) {
                var CanvasCoordinates = Viewer.scene.cartesianToCanvasCoordinates(viewData.chartPosition);
                if (!CanvasCoordinates) return;
                let _x = -viewData.chartDiv.offsetWidth / 2;
                let _y = 20;
                viewData.chartDiv.style.left = CanvasCoordinates.x + _x + "px";
                viewData.chartDiv.style.top = CanvasCoordinates.y + _y + "px";
            }
        });
    }
    viewData.chartDiv.style.display = 'block';
    viewData.ChartDataTitle.innerHTML = value;
    var CanvasCoordinates = Viewer.scene.cartesianToCanvasCoordinates(viewData.chartPosition);
    if (!CanvasCoordinates) return;
    let _x = -viewData.chartDiv.offsetWidth / 2;
    let _y = 20;
    viewData.chartDiv.style.left = CanvasCoordinates.x + _x + "px";
    viewData.chartDiv.style.top = CanvasCoordinates.y + _y + "px";

}

//关闭
function closeChartData() {
    if (viewData.chartPosition && viewData.chartDiv) {
        viewData.chartDiv.style.display = 'none';
        viewData.chartPosition = undefined;
    }
}

window.editGraphic = {};

//文本点
$('#btn1').click(function () {
    var handel = sgworld.AttachEvent('OnLButtonClk', function (x, y, movement) {
        var degrees = sgworld.Navigate.getMouseDegrees(movement);

        //添加文本标签
        var position = sgworld.Creator.CreatePosition(degrees.lon, degrees.lat, degrees.height, 1, 0, 0, 0, 300);
        var label = sgworld.Creator.CreateLabel(position, "test", '', { verticalOrigin: Cesium.VerticalOrigin.BOTTOM }, "0", 'test');
        window.propKind = 0;
        editGraphic.entity = label.item;
        editGraphic.graphic = label.item.label;
        popupRes('文本点属性', 350, 550, 'HTML/pointProp.html', null);
        //移除事件
        handel.destroy();
    });
})

//图片点
$('#btn2').click(function () {
    var handel = sgworld.AttachEvent('OnLButtonClk', function (x, y, movement) {
        var degrees = sgworld.Navigate.getMouseDegrees(movement);

        var position = sgworld.Creator.CreatePosition(degrees.lon, degrees.lat, degrees.height, 1, 0, 0, 0, 300);
        //添加图片标签
        var imageLabel = sgworld.Creator.CreateImageLabel(position, "http://36.7.136.132:1988/sdkdemo/src/static/image/mark.png", { verticalOrigin: Cesium.VerticalOrigin.BOTTOM }, 0, "标签点");

        //移除事件
        handel.destroy();
    });
})

//线
$('#btn3').click(function () {
    var entityPolyline = {
        material: Cesium.Color.fromAlpha(Cesium.Color.LIME, 0.6),
        clampToGround: true,
    };
    var en = sgworld.Creator.CreatePolylinePlus(entityPolyline, function (a) {

    });
})

//面
$('#btn4').click(function () {
    var entityPolygon = {
        material: Cesium.Color.fromAlpha(Cesium.Color.LIME, 0.6)
    };
    var en = sgworld.Creator.CreatePolygonPlus(entityPolygon, function (a) {

    });
})